package com.cstar.learnlang.RestControllers;

import java.util.List;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.SessionAttributes;
import org.springframework.web.servlet.ModelAndView;

import com.cstar.learnlang.DataForms.FavVocabularyListDataForm;
import com.cstar.learnlang.DataForms.NewVocabularyListDataForm;
import com.cstar.learnlang.DataForms.SearchVocabularyListDataForm;
import com.cstar.learnlang.PageControllers.HomePageController;
import com.cstar.learnlang.PageControllers.VocabularyPageController;
import com.cstar.learnlang.RowMappers.FavVocListRowMapper;
import com.cstar.learnlang.RowMappers.UserVocListRowMapper;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
 
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;

@Controller
@RequestMapping(value={"", 
		"/vocabularyPage/manageVocListSearch", 
		"/vocabularyPage/favVocListSearch", 
		"/vocabularyPage/favVocList/{rowId}"})
@SessionAttributes
public class FavVocListRestController {
	private static final Logger logger = LoggerFactory.getLogger(FavVocListRestController.class);
	@Autowired private JdbcTemplate jdbcRegisterInfoTemplate;
	@Autowired private HomePageController homePageController;
	@Autowired private VocabularyPageController vocPageController;
	@RequestMapping(value = "/vocabularyPage/favVocList/{rowId}", method = RequestMethod.GET)
	@ResponseBody
	public FavVocabularyListDataForm favVocListGet(
			HttpServletRequest request,
			HttpSession session,
			@PathVariable String rowId) {
		logger.info("favVocListGet rowId:{}", new String[] {rowId});
		String sql = "SELECT * FROM VOCABULARY_LIST WHERE id = ? AND USER_ID = ?";
		@SuppressWarnings("unchecked")
		List<FavVocabularyListDataForm> rs = jdbcRegisterInfoTemplate.query(sql, new Object[] {
				rowId,
				(String)session.getAttribute("userid")
				}, new FavVocListRowMapper());
		if (rs.size() == 0) {
			return new FavVocabularyListDataForm();
		} // if
		return rs.get(0);
	} // favVocListGet
	@RequestMapping(value = "/vocabularyPage/favVocListSearch", method = RequestMethod.POST)
	public ModelAndView favVocListSearch(
			HttpServletRequest request,
			@RequestParam (value="pageSize", required=false) String pageSize,
			@RequestParam (value="pageIdx", required=false) String pageIdx, // pageIdx is one based
    		@ModelAttribute("searchFavVocListInfo") SearchVocabularyListDataForm searchFavVocListInfo, 
			BindingResult result) {
		logger.info("favVocListSearch pageSize:{}, pageIdx:{}", new String[] {pageSize, pageIdx});
		HttpSession session = request.getSession();
		pageSize = homePageController.null2Empty(pageSize);
		pageIdx = homePageController.null2Empty(pageIdx);
		searchFavVocListInfo.setPageIdx(pageIdx);
		searchFavVocListInfo.setPageSize(pageSize);
		ModelAndView mv = new ModelAndView ("/vocabularyPage");
		mv.getModelMap().addAttribute("searchFavVocListInfo", searchFavVocListInfo); // return search criteria
		session.setAttribute("searchFavVocListInfo", searchFavVocListInfo); // set search criteria
        mv = vocPageController.populatePageModel (session, mv);
		session.setAttribute("leftNavItemIdx", "1");
		return mv;
	} // favVocListSearch
	@RequestMapping(value = "/vocabularyPage/manageVocListSearch", method = RequestMethod.POST)
	@ResponseBody
	public ModelAndView manageVocListSearch(
			HttpServletRequest request,
			@RequestParam (value="pageSize", required=false) String pageSize,
			@RequestParam (value="pageIdx", required=false) String pageIdx, // pageIdx is one based
			@ModelAttribute("searchManageVocListInfo") SearchVocabularyListDataForm searchManageVocListInfo) {
		logger.info("manageVocListSearch pageSize:{}, pageIdx:{}", new String[] {pageSize, pageIdx});
		HttpSession session = request.getSession();
		pageSize = homePageController.null2Empty(pageSize);
		pageIdx = homePageController.null2Empty(pageIdx);
		searchManageVocListInfo.setPageIdx(pageIdx);
		searchManageVocListInfo.setPageSize(pageSize);
		ModelAndView mv = new ModelAndView ("/vocabularyPage");
		mv.getModelMap().addAttribute("searchManageVocListInfo", searchManageVocListInfo); // return search criteria
		session.setAttribute("searchManageVocListInfo", searchManageVocListInfo); // set search criteria
		mv = vocPageController.populatePageModel (session, mv);
		session.setAttribute("leftNavItemIdx", "2");
		return mv;
	} // manageVocListSearch
	@RequestMapping(value = "/vocabularyPage/favVocList/{rowId}", method = RequestMethod.DELETE)
	public ModelAndView favVocListDelete(
			HttpServletRequest request,
			HttpServletResponse response,
			HttpSession session,
			@PathVariable String rowId) {
		logger.info("favVocListDelete id: {}", new String[] {rowId});
		String sql = "DELETE FROM SAVED_VOCABULARY_LISTS WHERE id = ? AND user_Id = ?";
		ModelAndView mv = new ModelAndView ("redirect:/vocabularyPage");
		jdbcRegisterInfoTemplate.update(sql, new Object[] {rowId, (String)session.getAttribute("userid")});
		session.setAttribute("serverReturnCode", "Success:Selected vocabulary is removed from favorites");
		session.setAttribute("leftNavItemIdx", "1");
		return vocPageController.populatePageModel(session, mv);
	} // favVocListDelete
	@RequestMapping(value="/vocabularyPage/favVocList", method = RequestMethod.POST)
    public ModelAndView favVocListCreate(
    		HttpServletRequest request,
    		@RequestParam("uid") String user_id,
    		@RequestParam("vid") String voc_id,
    		@RequestParam("lnx") String leftNavItemIdx,
    		@RequestParam("page") String redirPage) {
		HttpSession session = request.getSession();
		logger.info("favVocListCreate");
		String sql;
		ModelAndView mv = new ModelAndView ("redirect:/" + redirPage);
		sql = "SELECT COUNT(*) FROM SAVED_VOCABULARY_LISTS WHERE user_id = ? AND voclist_id = ?";
		int count = jdbcRegisterInfoTemplate.queryForInt(sql, new Object[] {user_id, voc_id});
		if (count != 0) {
			session.setAttribute("serverReturnCode", "Error:Vocabulary list is already in your favorites");
			session.setAttribute("leftNavItemIdx", leftNavItemIdx);
		} else {
			sql = "INSERT INTO SAVED_VOCABULARY_LISTS (USER_ID, VOCLIST_ID) VALUES (?, ?)";
			jdbcRegisterInfoTemplate.update(sql, new Object[] {user_id, voc_id});
			session.setAttribute("serverReturnCode", "Success:Vocabulary is added to your favorites");
			session.setAttribute("leftNavItemIdx", leftNavItemIdx);
		} // if
		logger.info("newVocabularyListPost sid:{} page: {} leftNavItemIdx:{}", new String[] {session.getId(), redirPage, leftNavItemIdx});
		return vocPageController.populatePageModel (session, mv);
    } // favVocListCreate 
	@ModelAttribute("searchManageVocListInfo")
    public SearchVocabularyListDataForm searchManageVocListInfo() {
		SearchVocabularyListDataForm data = new SearchVocabularyListDataForm();
		data.setLangMap(VocabularyPageController.langMap);
        return data;
    } // searchManageVocListInfo
	@ModelAttribute("searchFavVocListInfo")
	public SearchVocabularyListDataForm searchFavVocListInfo() {
		SearchVocabularyListDataForm data = new SearchVocabularyListDataForm();
		data.setLangMap(VocabularyPageController.langMap);
		return data;
	} // searchFavVocListInfo
	@ModelAttribute("searchVocabularyListInfo")
	public SearchVocabularyListDataForm searchVocabularyListInfo() {
		SearchVocabularyListDataForm data = new SearchVocabularyListDataForm();
		data.setLangMap(VocabularyPageController.langMap);
		return data;
	} // searchVocabularyListInfo
	@ModelAttribute("newVocabularyListInfo")
    public NewVocabularyListDataForm newVocabularyListInfo() {
        return new NewVocabularyListDataForm();
    } // newVocabularyListInfo
} // VocListRestController
